﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Microsoft.Xna.Framework.Media;
using Microsoft.Xna.Framework;
using System.IO.IsolatedStorage;
using Microsoft.Phone.Tasks;
using System.Windows.Threading;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using Microsoft.Phone.BackgroundAudio;

namespace iMusik
{
    public partial class PlayMusic : PhoneApplicationPage
    {
        private DispatcherTimer _timer;
        private List<string> _playListOffline;
        private List<iMusik.Mp3ZingOnline.Mp3Song> _playListOnline;
        private int _currentSong = 0;
        private bool _isLoop = false;
        private int _currentSongLoop = 0;

        const int prevButton = 0;
        const int playButton = 1;
        const int nextButton = 2;
        const int loopButton = 3;

        public PlayMusic()
        {
            InitializeComponent();

            BackKeyPress += MainPage_BackKeyPress;
        }

        void MainPage_BackKeyPress(object sender, System.ComponentModel.CancelEventArgs e)
        {
            string uri = "/Mp3ZingPage.xaml";
            NavigationService.Navigate(new Uri(uri, UriKind.Relative));
        }

        private void UpdatePlayButton()
        {
            if (PlayerAudio.CurrentState == MediaElementState.Playing)
            {
                ((ApplicationBarIconButton)(ApplicationBar.Buttons[playButton])).IconUri = new Uri("/Assets/Icons/appbar.transport.pause.rest.png", UriKind.Relative);
                ((ApplicationBarIconButton)(ApplicationBar.Buttons[playButton])).Text = "Pause";
            }
            else
            {
                ((ApplicationBarIconButton)(ApplicationBar.Buttons[playButton])).IconUri = new Uri("/Assets/Icons/appbar.transport.play.rest.png", UriKind.Relative);
                ((ApplicationBarIconButton)(ApplicationBar.Buttons[playButton])).Text = "Play";
            }
        }

        private void UpdateLoopButton()
        {
            if (_isLoop)
                ((ApplicationBarIconButton)(ApplicationBar.Buttons[loopButton])).IconUri = new Uri("/Assets/Icons/appbar.transport.check.rest.png", UriKind.Relative);
            else
                ((ApplicationBarIconButton)(ApplicationBar.Buttons[loopButton])).IconUri = new Uri("/Assets/Icons/appbar.transport.loop.rest.png", UriKind.Relative);
        }

        private void UpdateButtons(bool prevBtnEnabled, bool playBtnEnabled, bool nextBtnEnabled, bool loopBtnEnabled)
        {
            ((ApplicationBarIconButton)(ApplicationBar.Buttons[prevButton])).IsEnabled = prevBtnEnabled;
            ((ApplicationBarIconButton)(ApplicationBar.Buttons[playButton])).IsEnabled = playBtnEnabled;
            ((ApplicationBarIconButton)(ApplicationBar.Buttons[nextButton])).IsEnabled = nextBtnEnabled;
            ((ApplicationBarIconButton)(ApplicationBar.Buttons[loopButton])).IsEnabled = loopBtnEnabled;
        }

        private void UpdateState(object sender, EventArgs e)
        {
            sldPosition.Value = (int)PlayerAudio.Position.TotalSeconds;

            TimeSpan position = new TimeSpan();
            position = PlayerAudio.Position;
            if (position.Hours >= 1)
            {
                txtBlock1.Text = string.Format("{0:d2}:{1:d2}:{2:d2}", position.Hours, position.Minutes, position.Seconds);
            }
            else
            {
                txtBlock1.Text = string.Format("{0:d2}:{1:d2}", position.Minutes, position.Seconds);
            }

            TimeSpan timeRemaining = new TimeSpan();
            timeRemaining = PlayerAudio.NaturalDuration.TimeSpan - position;
            if (position.Hours >= 1)
            {
                txtBlock2.Text = string.Format("-{0:d2}:{1:d2}:{2:d2}", timeRemaining.Hours, timeRemaining.Minutes, timeRemaining.Seconds);
            }
            else
            {
                txtBlock2.Text = string.Format("-{0:d2}:{1:d2}", timeRemaining.Minutes, timeRemaining.Seconds);
            }
        }

        private void SetupTimer()
        {
            _timer = new DispatcherTimer();
            StartTimer();
        }

        private void StartTimer()
        {
            _timer.Tick += _timer_Tick;
            _timer.Start();
        }

        private void _timer_Tick(object sender, object e)
        {
            UpdateState(null, null);
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            LoadListSongs(e);
            base.OnNavigatedTo(e);
        }

        private void PlayOneSong(string temp)
        {
            PlayerAudio.Source = new Uri(temp, UriKind.RelativeOrAbsolute);
            PlayerAudio.AutoPlay = true;
            SongName.Text = "Bài hát: " + _playListOnline[_currentSong].SongName;
            SingerName.Text = "Ca sĩ: " + _playListOnline[_currentSong].SingerName;
        }

        private void LoadListSongs(NavigationEventArgs e)
        {
            _playListOnline = new List<iMusik.Mp3ZingOnline.Mp3Song>();

            try
            {
                _playListOnline.Add( PhoneApplicationService.Current.State["param"] as iMusik.Mp3ZingOnline.Mp3Song);
                PlayOneSong(_playListOnline[_currentSong].DirectLink);
            }
            catch
            {
                MessageBox.Show("Error");
            }          

            UpdateButtons(false, true, true, true);

            if (_playListOnline.Count == 1)
            {
                UpdateButtons(false, true, false, true);
            }
        }

        private void preButton_Click(object sender, EventArgs e)
        {
            //Offline
            //PlayOneSong(_playListOffline[--_currentSong]);
            //if (_currentSong == 0)
            //{
            //    btnBack.IsEnabled = false;
            //}
            //btnNext.IsEnabled = true;
            //_isLoop = false;

            //Online
            if (_currentSong == 0)
                return;
            PlayOneSong(_playListOnline[--_currentSong].DirectLink);
            if (_currentSong == 0)
                UpdateButtons(false, true, true, true);
            else
                UpdateButtons(true, true, true, true);
            _isLoop = false;
            UpdateLoopButton();
        }

        private void playButton_Click(object sender, EventArgs e)
        {
            if (PlayerAudio.CurrentState == MediaElementState.Playing)
            {
                PlayerAudio.Pause();
            }
            else
            {
                PlayerAudio.Play();
            }
        }

        private void nextButton_Click(object sender, EventArgs e)
        {
            //Offline
            //PlayOneSong(_playListOffline[++_currentSong]);
            //if (_currentSong == _playListOffline.Count - 1)
            //{
            //    btnNext.IsEnabled = false;
            //}
            //btnBack.IsEnabled = true;
            //_isLoop = false;

            //Online
            if (_currentSong + 1 == _playListOnline.Count)
                return;
            PlayOneSong(_playListOnline[++_currentSong].DirectLink);
            if (_currentSong == _playListOnline.Count - 1)
                UpdateButtons(true, true, false, true);
            else
                UpdateButtons(true, true, true, true);
            _isLoop = false;
            UpdateLoopButton();
        }

        private void loopButton_Click(object sender, EventArgs e)
        {
            _isLoop = !_isLoop;
            _currentSongLoop = _currentSong;
            UpdateLoopButton();
        }

        private void PlayerAudio_CurrentStateChanged(object sender, RoutedEventArgs e)
        {
            if (PlayerAudio.CurrentState == MediaElementState.Playing)
            {
                _timer.Start();
            }

            if (PlayerAudio.CurrentState == MediaElementState.Paused)
            {
                _timer.Stop();
            }

            if (PlayerAudio.CurrentState == MediaElementState.Stopped)
            {
                _timer.Stop();
            }
            UpdatePlayButton();
        }

        private void PlayerAudio_MediaEnded(object sender, RoutedEventArgs e)
        {
            PlayerAudio.Stop();

            //Offline
            //if (_isLoop == true)
            //{
            //    PlayOneSong(_playListOffline[_currentSong]);
            //}
            //else
            //{
            //    if (_playListOffline.Count >= 2 && _currentSong < _playListOffline.Count - 1)
            //    {
            //        PlayOneSong(_playListOffline[++_currentSong]);
            //    }
            //}

            //Online
            if (_isLoop)
            {
                PlayOneSong(_playListOnline[_currentSong].DirectLink);
            }
            else
            {
                if (_playListOnline.Count >= 2 && _currentSong < _playListOnline.Count - 1)
                {
                    PlayOneSong(_playListOnline[++_currentSong].DirectLink);
                }
            }

            if (_currentSong == _playListOnline.Count - 1)
                UpdateButtons(true, true, false, true);
            _timer.Stop();
            UpdateState(null, null);
        }

        private void PlayerAudio_MediaFailed(object sender, ExceptionRoutedEventArgs e)
        {
            MessageBox.Show("Error");
        }

        private void PlayerAudio_MediaOpened(object sender, RoutedEventArgs e)
        {
            sldPosition.Maximum = (int)PlayerAudio.NaturalDuration.TimeSpan.TotalSeconds;
            SetupTimer();
        }

        private void sldPosition_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            if (sldPosition != null && e.NewValue - e.OldValue != 1.0)
            {
                TimeSpan ts = new TimeSpan(0, 0, (int)sldPosition.Value);
                PlayerAudio.Position = ts;
            }
        }

        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            //BackgroundAudioPlayer.Instance.Track = new AudioTrack(PlayerAudio.Source, "", "", "", null);
            //BackgroundAudioPlayer.Instance.Position = PlayerAudio.Position;
            //PlayerAudio.Stop();
            //BackgroundAudioPlayer.Instance.Play();
        }
    }
}